<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo json_encode(["code" => "401", "error" => "未授权访问"]);
    exit();
}

include 'config.php';

// 验证参数
if (!isset($_GET['kamiList']) || empty($_GET['kamiList'])) {
    echo json_encode(["code" => "400", "error" => "参数错误"]);
    exit();
}

// 分割卡密列表并过滤空值
$kamiList = explode(',', urldecode($_GET['kamiList']));
$kamiList = array_filter(array_map('trim', $kamiList));

if (empty($kamiList)) {
    echo json_encode(["code" => "400", "error" => "卡密列表为空"]);
    exit();
}

// 构建预处理 SQL
$placeholders = implode(',', array_fill(0, count($kamiList), '?'));
$sql = "DELETE FROM kami WHERE kami IN ($placeholders)";
$stmt = $conn->prepare($sql);

if (!$stmt) {
    echo json_encode(["code" => "500", "error" => "数据库错误: " . $conn->error]);
    exit();
}

// 动态绑定参数
$types = str_repeat('s', count($kamiList));
$stmt->bind_param($types, ...$kamiList);

if ($stmt->execute()) {
    $affectedRows = $stmt->affected_rows;
    if ($affectedRows > 0) {
        echo json_encode(["code" => "200", "msg" => "成功删除 {$affectedRows} 条记录"]);
    } else {
        echo json_encode(["code" => "404", "error" => "未找到匹配的卡密"]);
    }
} else {
    echo json_encode(["code" => "500", "error" => "执行失败: " . $stmt->error]);
}

$stmt->close();
$conn->close();
?>